#include "FileLoader.h"

FileLoader::FileLoader()
{
	// Empty
}

FileLoader::~FileLoader()
{
	// Empty
}

bool FileLoader::Load(const String &fileName, Buffer &buffer)
{
	if(LoadFromFile(fileName, buffer)) return true;

	Error::Instance().SetMessage("Unable to load \"" + fileName + "\", file does not exist!");
	return false;
}

bool FileLoader::LoadFromFile(const String& fileName, Buffer& buffer)
{
	u32 size;
	std::ifstream file;

	file.open(fileName.c_str(), std::ios::in | std::ios::binary);
	if(file.fail()) return false;

	file.seekg(0, std::ios::end);
	size = file.tellg();
	file.seekg(0, std::ios::beg);

	if(!buffer.Resize(size)) return false;

	file.read(buffer.GetData(), buffer.GetSize());

	return true;
}

bool FileLoader::SaveToFile(const String &fileName, Buffer &buffer)
{
	std::ofstream file;

	file.open(fileName.c_str(), std::ios::out | std::ios::binary);
	if(file.fail())
	{
		Error::Instance().SetMessage("Unable to save \"" + fileName + "\"!");
		return false;
	}

	file.write(buffer.GetData(), buffer.GetSize());

	return true;
}